package pro.images.server.web;

import com.yy.kit.collections.YYListKits;
import com.yy.kit.collections.YYMapKits;
import com.yy.kit.file.YYFileKits;
import com.yy.kit.file.YYFileTypeKits;
import com.yy.kit.log.YYLogKits;
import com.yy.pojo.image.TImages;
import com.yy.pojo.image.TImagesExample;
import io.shardingjdbc.core.keygen.DefaultKeyGenerator;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import pro.images.server.mapper.TImagesMapper;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 上传及获取图片的接口控制器
 * </p>
 *
 * @author 杨阳
 * @since 2017年10月16日
 */
@Controller
@RequestMapping("/images")
public class ImagesServerController {

    @Autowired
    private TImagesMapper tImagesMapper;

    /**
     * <p>
     * 上传bug图片的方法,副文本编辑器使用
     * </p>
     *
     * @param file 上传后的文件
     * @return { "code": 0 //0表示成功，其它失败 ,"msg": "" //一般上传失败后返回 , "data": { "src": "图片路径" ,"title": "图片名称" } }
     * @author 杨阳
     * @since 2017年9月6日
     */
    @RequestMapping(value = "/uploadimage", method = RequestMethod.POST)
    @ApiOperation(value = "上传图片", httpMethod = "POST", notes = "上传图片，先判断图片的md5，如果表中已经存在，直接返回就可以，如果不存在，再上传，以二进制方式存储在数据库中")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "file", value = "上传的文件", required = true, paramType = "form")
    })
    @ResponseBody
    public Map<String, Object> uploadImage(@RequestParam MultipartFile file) {
        YYLogKits.info(ImagesServerController.class, "┌───────────────────────────────────────────────────────────────────────────┐");
        YYLogKits.info(ImagesServerController.class, "├开始上传图片:");
        Map<String, Object> result = YYMapKits.createHashMap();
        Map<String, String> data = YYMapKits.createStringHashMap();
        try {
            if (file.isEmpty()) {
                result.put("code", "3");
                result.put("msg", "请选择要上传的图片!!");
                YYLogKits.info(ImagesServerController.class, "├没有发现要上传的文件，请选择后再上传!");
                YYLogKits.info(ImagesServerController.class, "└───────────────────────────────────────────────────────────────────────────┘");
                return result;
            }

            byte[] fileByte = file.getBytes();
            String md5 = YYFileKits.getFileMd5(fileByte);
            YYLogKits.info(ImagesServerController.class, "├上传的文件md5:{}", md5);

            long size = file.getSize();
            long m = size / 1024 / 1024;
            if (m > 1) {
                // 说明图片文件超过一M,需要返回，不能通过
                result.put("code", "4");
                result.put("msg", "图片文件大小不可以超过1M!!");
                return result;
            }
            YYLogKits.info(ImagesServerController.class, "├上传的文件size:{}M", m);

            String fileName = file.getOriginalFilename();
            YYLogKits.info(ImagesServerController.class, "├上传的文件名称:{}", fileName);

            String suffixName = fileName.substring(fileName.lastIndexOf(".") + 1);
            YYLogKits.info(ImagesServerController.class, "├文件的后缀名:{}", suffixName);
            boolean isImg = YYFileTypeKits.isImage(suffixName);
            if (!isImg) {
                result.put("code", "5");
                result.put("msg", "只可以上传图片文件!");
                return result;
            }

            // 根据md5查询是否已经上传过文件
            TImagesExample example = new TImagesExample();
            example.createCriteria().andMd5EqualTo(md5);
            List<TImages> imgList = tImagesMapper.selectByExample(example);
            if (YYListKits.isNotEmpty(imgList)) {
                YYLogKits.info(ImagesServerController.class, "├图片以前上传过,不需要再上传,md5:{},id:{}", md5, imgList.get(0).getId());
                result.put("code", 0);
                result.put("msg", "");

                data.put("src", "/images/getimg/" + imgList.get(0).getId());
                data.put("title", file.getOriginalFilename());

                result.put("data", data);
                YYLogKits.info(ImagesServerController.class, "├从数据库中获取图片成功!");
                YYLogKits.info(ImagesServerController.class, "└───────────────────────────────────────────────────────────────────────────┘");
                return result;
            }

            TImages uploadImg = new TImages();

            DefaultKeyGenerator generator = new DefaultKeyGenerator();
            Long imgId = generator.generateKey().longValue();

            uploadImg.setId(imgId);
            uploadImg.setMd5(md5);
            uploadImg.setSize(size);
            uploadImg.setImage(fileByte);
            uploadImg.setCreate_date(new Date());

            int b = tImagesMapper.insert(uploadImg);
            YYLogKits.info(ImagesServerController.class, "├插入数据库,是否成功:{}", b > 0);
            result.put("code", 0);
            result.put("msg", "");

            data.put("src", "/images/getimg/" + imgId);
            data.put("title", file.getOriginalFilename());

            result.put("data", data);
            YYLogKits.info(ImagesServerController.class, "├上传成功!");
            YYLogKits.info(ImagesServerController.class, "└───────────────────────────────────────────────────────────────────────────┘");
            return result;
        } catch (IllegalStateException e) {
            result.put("code", 1);
            result.put("msg", "IllegalStateException");
            YYLogKits.printException(this.getClass(), e.getMessage());
            return result;
        } catch (IOException e) {
            result.put("code", 2);
            result.put("msg", "IOException");
            YYLogKits.printException(this.getClass(), e.getMessage());
            return result;
        }
    }


    /**
     * <p>
     * 从数据库中获取到图片，显示在页面上
     * </p>
     *
     * @param id       图片id
     * @param response {@link HttpServletResponse}
     * @author 杨阳
     * @since 2017年10月16日
     */
    @RequestMapping(value = "/getImage/{id}", method = RequestMethod.GET)
    @ApiOperation(value = "从数据库中获取到图片，显示在页面上", httpMethod = "GET", notes = "从数据库中获取到图片，显示在页面上,以流的方式写出")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id", value = "图片ID", required = true, paramType = "path")
    })
    @ResponseBody
    public TImages getImage(@PathVariable("id") String id, HttpServletResponse response) {
        return tImagesMapper.selectByPrimaryKey(Long.parseLong(id));
    }
}
